package ysq.xyg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.dao.BaseJobDao;
import ysq.xyg.model.BaseJob;
import ysq.xyg.service.BaseJobService;
import ysq.xyg.util.SchedulerUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 商品分类实现
 *
 * @author congcong tao
 * @date 2018/8/7 11:46
 */
@Service("baseJobService")
public class BaseJobServiceImpl extends BaseServiceImpl<BaseJob> implements BaseJobService {


    @Autowired
    private Scheduler scheduler;
    @Resource
    private BaseJobDao baseJobDao;
    @Autowired
    public void setBaseJobDao(BaseJobDao baseJobDao) {
        this.baseDao = baseJobDao;
    }

    @PostConstruct
    public void initScheduleJob() {
        List<BaseJob> jobs = baseJobDao.selectAll();
        if (jobs == null || jobs.size() == 0) {
            return;
        }
        for (BaseJob record : jobs) {
            String name = record.getJobName();
            String group = record.getJobGroup();
            CronTrigger cronTrigger = SchedulerUtils.getCronTrigger(scheduler, name, group);
            if (cronTrigger == null) {
                SchedulerUtils.createScheduleJob(record, scheduler);
            } else {
                SchedulerUtils.updateScheduleJob(scheduler, record);
            }
        }
    }
    
    @Override
    public PageInfo<BaseJob> pageInfo(BaseJob baseJob, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        // 通用Example查询
        Example example = new Example(BaseJob.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(baseJob.getStatus())) {
            criteria.andEqualTo("status", baseJob.getStatus());
        }
        List<BaseJob> list = baseJobDao.selectByExample(example);
        return new PageInfo<BaseJob>(list);
    }
}
